package com.yunhe.marketing.task;

import com.yunhe.common.util.RedisClient;
import com.yunhe.marketing.domain.CompanyHeat;
import com.yunhe.marketing.service.ICompanyHeatService;
import com.yunhe.common.util.CollectionUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author zhengbo
 * @date 2021/3/16 13:58
 */
@Component
@EnableScheduling
public class CompanyHeatScheduled {

    private Logger logger = Logger.getLogger(CompanyHeatScheduled.class);

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private ICompanyHeatService iCompanyHeatService;

    /**redis key的部分前缀*/
    private static final String HEAT_COMPANY = "heat:company:";

    /**热度值的类型 这边默认是企业*/
    private static final String TYPE = "company";

    /**
     * 每分钟执行一次
     * 从redis拉去企业热度值存入mysql
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void handle(){
        logger.info("CompanyHeatScheduled is running");
        //查询redis中所有企业热度值的key
        Set<String> keys = redisClient.keys(HEAT_COMPANY + "*");
        if (CollectionUtil.isNotEmpty(keys)) {
            keys.forEach(key -> {
                logger.info("heatCompanyKey is " + key);
                //根据key从redis中获取企业热度值
                String heatValueChange = redisClient.get(key);
                if (StringUtils.isNotEmpty(heatValueChange)) {
                    //value的格式为value: 2;2;0.834031

                    //key的格式为heat:company:34253
                    //分割字符串拿到itemId
                    String[] keyStr = key.split(":");
                    String itemId = keyStr[2];
                    logger.info("heatCompanyItemId is " + itemId);

                    //入库
                    CompanyHeat companyHeat = new CompanyHeat();
                    companyHeat.setHeat(heatValueChange);
                    companyHeat.setItemId(Long.valueOf(itemId));
                    companyHeat.setType(TYPE);
                    iCompanyHeatService.saveOrUpdate(companyHeat);
                }
            });
        }
        logger.info("CompanyHeatScheduled finish");
    }
}
